<?php
class Core_Controller_Controllerloader {
	
	/**
	 * @var $secure
	 */
	public $secure;
	
	/**
	 * constructor
	 */
	public function __construct(){
		
		$this->secure = new Core_Data_Secure();
		
	}
	
	/**
	 * load controller
	 * 
	 * @param string $request
	 */
	public function getController($request, array $postVars){
		
		$parsed = $this->getParsed($request);
		
		$page = $this->getPage($parsed);
		
		$getVars = $this->getGetVars($parsed);
		$getVars = $this->secure->htmlSpecialChars($getVars);
		
		$filePath = $this->getPath($page);
		
		$this->loadFile($filePath);
		
		$this->classInitialization($page, $filePath, $getVars, $postVars);
		
	}
	
	/**
	 * initialization controller class
	 * 
	 * @param string $page
	 * @param string $filePath
	 * @param array $getVars
	 * @throws Exception
	 */
	public function classInitialization($page, $filePath, array $getVars, array $postVars){
		
		try {
			
			//modify page to fit naming convention
			$class = ucfirst($page) . '_Controller_' . ucfirst($page);
			
			//instantiate the appropriate class
			if (class_exists($class))
			{
				
				$controller = new $class;
				$controller->entryPoint($getVars, $postVars);
				
			}
			else {
				echo '<meta http-equiv="Refresh" content="0;url='.SITE_ROOT.'?index&page=index">'; 
			}
			
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		
	}
	
	/**
	 * get target
	 * 
	 * @param string $filePath
	 * @throws Exception
	 */
	public function loadFile($filePath){
		
		try {
			
			if(file_exists($filePath)){
				
				require_once $filePath;
				
			}
			
			else {
				
				 echo '<meta http-equiv="Refresh" content="0;url='.SITE_ROOT.'?index&page=index">';  
				
			}
			
		}
		catch(Exception $e){
			echo $e->getMessage();
		}
		
	}
	
	/**
	 * compute the path to the file
	 * 
	 * @param string $page
	 * @return string $filePath
	 */
	public function getPath($page){
		
		$filePath = basename(SERVER_ROOT) . "/" . basename($page) . "/" . basename("controllers") . "/" . basename($page) . ".php";

		return $filePath;
		
	}
	
	/**
	 * the rest of the array are get statements, parse them out
	 * 
	 * @param unknown $parsed
	 * @return multitype:multitype: $getVars
	 */
	public function getGetVars($parsed){
		
		$getVars = array();
		
		foreach ($parsed as $argument)
		{

			//split GET vars along '=' symbol to separate variable, values
			list($variable , $value) = explode('=' , $argument);
			$getVars[$variable] = urldecode($value);
		
		}
		
		return $getVars;
		
	}
	
	/**
	 * the page is the first element
	 * 
	 * @param array $parsed
	 * @return mixed $page
	 */
	public function getPage(array $parsed){
		$page = array_shift($parsed);
		return $page;
	}
	
	/**
	 * parse the page request and other GET variables
	 * 
	 * @param string $request
	 * @return multitype:
	 */
	public function getParsed($request){
		
		$parsed = explode('&', $request);
		
		return $parsed;
	
	}
	
}